package com.blyat.xsoft.gateway.ribbon.filter.global;

import com.blyat.xsoft.gateway.ribbon.filter.FilterOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Auther: syh
 * @Date: 2020/8/24
 * @Description: 全局过滤器：耗时统计
 */
public class ElapsedFilter implements GlobalFilter, Ordered {
    private static final Logger logger = LoggerFactory.getLogger(ElapsedFilter.class);

    @Override
    public int getOrder() {
        return FilterOrder.GLOBAL_ELAPSED_ORDER;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        Long startTime = System.currentTimeMillis();
        return chain.filter(exchange).then().then(Mono.fromRunnable(() -> {
            logger.info("request used time: " + (System.currentTimeMillis() - startTime));
        }));
    }
}
